package com.tbl.modules.agv.service.impl.webapi;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.tbl.modules.agv.dao.agv.AgvTaskDAO;
import com.tbl.modules.agv.dao.webapidao.WebApiDAO;
import com.tbl.modules.agv.entity.agvtask.AgvTask;
import com.tbl.modules.agv.service.webapi.client.WebApiClientService;
import com.tbl.modules.agv.util.Rbsc;
import com.tbl.modules.wms.constant.EmumConstant;
import com.tbl.modules.wms.dao.baseinfo.ShelfDAO;
import com.tbl.modules.wms.dao.interfacelog.InterfaceLogDAO;
import com.tbl.modules.wms.entity.baseinfo.Shelf;
import com.tbl.modules.wms2.dao.baseinfo.YclInventoryDAO;
import com.tbl.modules.wms2.dao.insidewarehouse.transferorder.TransferOrderDAO;
import com.tbl.modules.wms2.dao.insidewarehouse.transferorder.TransferOrderLineDAO;
import com.tbl.modules.wms2.dao.report.InventoryDao;
import com.tbl.modules.wms2.entity.baseinfo.YclInventory;
import com.tbl.modules.wms2.entity.insidewarehouse.transferorder.TransferOrderEntity;
import com.tbl.modules.wms2.entity.insidewarehouse.transferorder.TransferOrderLineEntity;
import com.tbl.modules.wms2.entity.report.YclInventoryEntity;
import org.apache.poi.ss.formula.functions.T;
import org.apache.taglibs.standard.lang.jstl.NullLiteral;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * http接口客户端实现
 * @author cxf
 */
@Service
public class WebApiClientServiceImpl extends ServiceImpl<WebApiDAO, T> implements WebApiClientService {

    /**
     * 日志打印
     */
    private final Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 接口日志
     */
    private InterfaceLogDAO interfaceLogDAO;
    /**
     * webapoi
     */
    private WebApiDAO webApiDAO;
    /**
     * 移库调拨单头
     */
    @Autowired
    private TransferOrderDAO transferOrderDAO;
    /**
     * 移库调拨单行
     */
    @Autowired
    private TransferOrderLineDAO transferOrderLineDAO;
    /**
     * 库存详情
     */
    @Autowired
    private InventoryDao inventoryDao;
    /**
     * 库位
     */
    @Autowired
    private ShelfDAO shelfDAO;
    /**
     * agv任务主表
     */
    @Autowired
    private AgvTaskDAO agvTaskDAO;

    /**
     * 原材料调拨入库：WMS生成AGV任务并发送给AMS
     * @param barCode 一维码（携带调拨明细主键或者是调拨单号+调拨行号）
     * @param locationFrom 点位信息
     * @return String
     */
    @Override
    public String storageInAddTask(String barCode, String locationFrom){
        //调拨单
        TransferOrderEntity transferOrderEntity = transferOrderDAO.selectOne(new TransferOrderEntity(){{
            setTranCode("???");
        }});
        //调拨明细
        TransferOrderLineEntity transferOrderLineEntity = transferOrderLineDAO.selectList(new EntityWrapper<TransferOrderLineEntity>()
                .eq("TRAN_ID", transferOrderEntity.getId())
                .eq("LINE_NUM", "?????")).get(0);

        AgvTask agvTask = new AgvTask();

        Map<String,Object> sendDataMap = Maps.newHashMap();
        //2：原材料入库
        sendDataMap.put("businessType", "4");
        //来源仓库号（调拨单中的调出子库）
        sendDataMap.put("whNoFrom",transferOrderEntity.getFromStoreCode());
        //目的仓库号（调拨单中的调入子库）
        sendDataMap.put("whNoTo",transferOrderEntity.getToStoreCode());
        //系统名称？
        sendDataMap.put("sysName","1");
        //设备名称？
        sendDataMap.put("deviceCode","1");
        //wms生成的最新agv任务号
        String taskNo = new DecimalFormat("000000000000").format(webApiDAO.selectSeqAgvTaskNo());
        sendDataMap.put("taskNo",taskNo);
        //批次号（物料的批次号）
        sendDataMap.put("batchNo",transferOrderLineEntity.getLotsNum());
        //任务序号、生成任务按照升序规则，不填默认为0
        sendDataMap.put("orderNo",0);
        //来源暂存位（点位信息）---这才是重点，上面的都是虚的
        sendDataMap.put("locationFrom",locationFrom);
        //获取原材料区的空库位
        List<Shelf> lstTargetShelf = shelfDAO.selectList(new EntityWrapper<Shelf>()
                .eq("AREA", EmumConstant.shelfArea.RAW_MATERIAL_AREA.getCode())
                .eq("STATE",EmumConstant.sheflState.AVAILABLE.getCode()));
        if (lstTargetShelf.size()>0){
            //目的暂存位（点位信息）---这才是重点，上面的都是虚的
            sendDataMap.put("locationTo",lstTargetShelf.get(0).getAgvPoint());
            agvTask.setLocationTo(lstTargetShelf.get(0).getAgvPoint());
        }else {
            return JSONObject.toJSONString(new HashMap<String, Object>(3){{
                put("success", "False");
                put("errCode", "001");
                put("errMsg", "没有可用的目标暂存位，原材料区库位已满！");
            }});
        }
        //优先级(数字越大优先级越高)
        sendDataMap.put("priority","1");
        //用以分区相同设备不同动作的流程
        sendDataMap.put("extParam","1");
        //拓展参数1
        sendDataMap.put("ext1","1");
        //拓展参数2
        sendDataMap.put("ext2","1");
        //拓展参数3
        sendDataMap.put("ext3","1");
        //来源库区,支持多个库区
        List<Map<String, Object>> areaFromList = new ArrayList<>();
        areaFromList.add(new HashMap<String, Object>(1){{
            put("areaCode","222");
        }});
        areaFromList.add(new HashMap<String, Object>(1){{
            put("areaCode","333");
        }});
        sendDataMap.put("areaFrom",areaFromList);
        //目的库区,支持多个库区
        List<Map<String, Object>> areaTo = new ArrayList<>();
        areaTo.add(new HashMap<String, Object>(1){{
            put("areaCode","555");
        }});
        areaTo.add(new HashMap<String, Object>(1){{
            put("areaCode","666");
        }});
        sendDataMap.put("areaTo",areaTo);

        //调用AMS生成AGV任务的接口
        String returnResult = Rbsc.httpPostWithJSON("http://10.102.11.242:7080/api/HHAms/AddTask", JSONObject.toJSONString(sendDataMap));

        //记录接口日志：生成了搬运任务后发送给AMS
        interfaceLogDAO.insertLog("AddTask","WMS-->>AMS 生成AGV任务发送给AMS", JSONObject.toJSONString(sendDataMap), returnResult,
                //AGV任务号，物料对应的批次号
                (String) sendDataMap.get("taskNo"), (String) sendDataMap.get("batchNo"));

        //生成的任务存入agv任务表
        agvTask.setBussinessType(EmumConstant.agvTaskType.MOVE_THE_STOREHOUSE.getCode());
        agvTask.setWhNoFrom(transferOrderEntity.getFromStoreCode());
        agvTask.setWhNoTo(transferOrderEntity.getToStoreCode());
        agvTask.setTaskNo(taskNo);
        agvTask.setBatchNo(transferOrderLineEntity.getLotsNum());
        agvTask.setLocationFrom(locationFrom);
        agvTask.setLocationTo(transferOrderEntity.getToStoreCode());
        agvTaskDAO.insert(agvTask);

        return returnResult;
    }


    /**
     * 原材料配送：WMS生成AGV任务并发送给AMS
     * @return String
     */
    @Override
    public String deliveryAddTask(){
        //MES到WMS叫料接口(叫料单)


        //获取库存中料数量最合适的一个库位作为来源库位
        String locationFrom;//库位对应的点位
        String batch_no;//批次号
        BigDecimal num = new BigDecimal("");//叫料单的数量
        //记录厂区和仓库号以便后面做库存加拣
        List<YclInventoryEntity> lstFromInventory = inventoryDao.selectList(new EntityWrapper<YclInventoryEntity>()
                .eq("MATERIAL_CODE", null)
                .ge("QUALITY",num)//大于等于需求的数量
                .orderBy("QUALITY"));
        if(lstFromInventory.size()>0){
            //遍历符合数据的库位，找到只存在单独这一种物料的库位
            YclInventoryEntity chooseInventory = new YclInventoryEntity();
            for(YclInventoryEntity entity:lstFromInventory){
                Map<String, Object> map =new HashMap<>(3);
                map.put("AREA_CODE",entity.getAreaCode());
                map.put("LOCATOR_CODE",entity.getLocatorCode());
                map.put("STORE_CODE",entity.getStoreCode());
                List<Map<String, Object>> list= inventoryDao.getCountByShelf(map);
                if (list.size()==1){
                    chooseInventory = entity;
                    break;
                }
            }
            batch_no = chooseInventory.getLotsNum();
            String locationCode = chooseInventory.getLocatorCode();
            String areaCode = chooseInventory.getAreaCode();//厂区
            String storeCode = chooseInventory.getStoreCode();//仓库
            //根据库位,仓库，厂区到货位表中获取唯一的agvpoint
           Shelf shelfFrom = shelfDAO.selectOne(new Shelf(){{
               setWarehouseCode(storeCode);
               setFactoryCode(areaCode);
               setCode(locationCode);
           }});
            locationFrom = shelfFrom.getAgvPoint();
        }else{
            return JSONObject.toJSONString(new HashMap<String, Object>(3){{
                put("success", "False");
                put("errCode", "001");
                put("errMsg", "库存中没有找到该库料！");
            }});
        }

        //循环库位表中所有得库位得到一个空库位作为目的库位
        List<Shelf> lstTargetShelf = shelfDAO.selectList(new EntityWrapper<Shelf>()
                .eq("AREA", EmumConstant.shelfArea.MACHINE_EDGE_AREA.getCode())
                .eq("STATE",EmumConstant.sheflState.AVAILABLE.getCode())
                .isNotNull("AGV_POINT"));
        String locationTo = null;
        for(Shelf shelf : lstTargetShelf){//循环查询readStockStatus接口查询空接口
            Map<String, Object>  readStock = readStockStatus(Integer.parseInt(shelf.getAgvPoint()));
            if(readStock.get("occupy").equals("0")){//1非空0空9点位不存在
                locationTo = shelf.getAgvPoint();
                break;
            }
        }
        //如果没有空位得话提示返回，有的话确认是目标暂存位置
        if (locationTo.isEmpty()){
            return JSONObject.toJSONString(new HashMap<String, Object>(3){{
                put("success", "False");
                put("errCode", "001");
                put("errMsg", "没有可用的目标暂存位，机边库区库位已满！");
            }});
        }
        AgvTask agvTask = new AgvTask();
        Map<String,Object> sendDataMap = Maps.newHashMap();
        //2：叫料
        sendDataMap.put("businessType", "1");
        //来源仓库号（调拨单中的调出子库）
        sendDataMap.put("whNoFrom",null);
        //目的仓库号（调拨单中的调入子库）
        sendDataMap.put("whNoTo",null);
        //系统名称？
        sendDataMap.put("sysName",null);
        //设备名称？
        sendDataMap.put("deviceCode",null);
        //wms生成的最新agv任务号
        String taskNo = new DecimalFormat("000000000000").format(webApiDAO.selectSeqAgvTaskNo());
        sendDataMap.put("taskNo",taskNo);
        //批次号（物料的批次号）
        sendDataMap.put("batchNo",null);
        //任务序号、生成任务按照升序规则，不填默认为0
        sendDataMap.put("orderNo",0);
        //来源暂存位（点位信息）---这才是重点，上面的都是虚的
        sendDataMap.put("locationFrom",locationFrom);
        //目的暂存位（点位信息）---这才是重点，上面的都是虚的
        sendDataMap.put("locationTo",locationTo);
        agvTask.setLocationTo(locationTo);
        //优先级(数字越大优先级越高)
        sendDataMap.put("priority","1");
        //用以分区相同设备不同动作的流程
        sendDataMap.put("extParam","1");
        //拓展参数1
        sendDataMap.put("ext1","1");
        //拓展参数2
        sendDataMap.put("ext2","1");
        //拓展参数3
        sendDataMap.put("ext3","1");
        //来源库区,支持多个库区
        List<Map<String, Object>> areaFromList = new ArrayList<>();
        areaFromList.add(new HashMap<String, Object>(1){{
            put("areaCode","222");
        }});
        areaFromList.add(new HashMap<String, Object>(1){{
            put("areaCode","333");
        }});
        sendDataMap.put("areaFrom",areaFromList);
        //目的库区,支持多个库区
        List<Map<String, Object>> areaTo = new ArrayList<>();
        areaTo.add(new HashMap<String, Object>(1){{
            put("areaCode","555");
        }});
        areaTo.add(new HashMap<String, Object>(1){{
            put("areaCode","666");
        }});
        sendDataMap.put("areaTo",areaTo);
        //调用AMS生成AGV任务的接口
        String returnResult = Rbsc.httpPostWithJSON("http://10.102.11.242:7080/api/HHAms/AddTask", JSONObject.toJSONString(sendDataMap));
        //记录接口日志：生成了搬运任务后发送给AMS
        interfaceLogDAO.insertLog("AddTask","WMS-->>AMS 生成AGV任务发送给AMS", JSONObject.toJSONString(sendDataMap), returnResult,
                //AGV任务号，物料对应的批次号
                (String) sendDataMap.get("taskNo"), (String) sendDataMap.get("batchNo"));
        //生成的任务存入agv任务表
        agvTask.setBussinessType(EmumConstant.agvTaskType.CALLING_FOR_MATERIAL.getCode());
        agvTask.setWhNoFrom(null);
        agvTask.setWhNoTo(null);
        agvTask.setTaskNo(taskNo);
        agvTask.setBatchNo(batch_no);
        agvTask.setLocationFrom(locationFrom);
        agvTask.setLocationTo(locationTo);
        agvTask.setDeliveryNum(num);
        agvTask.setMaterialCode(null);
        agvTaskDAO.insert(agvTask);
        return returnResult;
    }


    /**
     * 原材料退料：WMS生成AGV任务并发送给AMS
     * @return String
     */
    @Override
    public String returnAddTask(){
        //MES到WMS退料接口(退料单)



        //wms发送来源库位和物料信息还有数量
        BigDecimal num = new BigDecimal("");//叫料单的数量
        String batch_no = null;//批次号
        String locationFrom =null;
        //根据库位,仓库，厂区到货位表中获取唯一的agvpoint
        Shelf shelfFrom = shelfDAO.selectOne(new Shelf(){{
            setWarehouseCode(null);
            setFactoryCode(null);
            setCode(null);
        }});
        locationFrom = shelfFrom.getAgvPoint();


        //循环库位表中所有得库位得到一个空库位作为目的库位
        List<Shelf> lstTargetShelf = shelfDAO.selectList(new EntityWrapper<Shelf>()
                .eq("AREA", EmumConstant.shelfArea.RAW_MATERIAL_AREA.getCode())
                .eq("STATE",EmumConstant.sheflState.AVAILABLE.getCode())
                .isNotNull("AGV_POINT"));
        String locationTo = null;
        for(Shelf shelf : lstTargetShelf){//循环查询readStockStatus接口查询空接口
            Map<String, Object>  readStock = readStockStatus(Integer.parseInt(shelf.getAgvPoint()));
            if(readStock.get("occupy").equals("0")){//1非空0空9点位不存在
                locationTo = shelf.getAgvPoint();
                break;
            }
        }
        //如果没有空位得话提示返回，有的话确认是目标暂存位置
        if (locationTo.isEmpty()){
            return JSONObject.toJSONString(new HashMap<String, Object>(3){{
                put("success", "False");
                put("errCode", "001");
                put("errMsg", "没有可用的目标暂存位，原材料存储库区库位已满！");
            }});
        }
        AgvTask agvTask = new AgvTask();
        Map<String,Object> sendDataMap = Maps.newHashMap();
        //2：叫料
        sendDataMap.put("businessType", "1");
        //来源仓库号（调拨单中的调出子库）
        sendDataMap.put("whNoFrom",null);
        //目的仓库号（调拨单中的调入子库）
        sendDataMap.put("whNoTo",null);
        //系统名称？
        sendDataMap.put("sysName",null);
        //设备名称？
        sendDataMap.put("deviceCode",null);
        //wms生成的最新agv任务号
        String taskNo = new DecimalFormat("000000000000").format(webApiDAO.selectSeqAgvTaskNo());
        sendDataMap.put("taskNo",taskNo);
        //批次号（物料的批次号）
        sendDataMap.put("batchNo",null);
        //任务序号、生成任务按照升序规则，不填默认为0
        sendDataMap.put("orderNo",0);
        //来源暂存位（点位信息）---这才是重点，上面的都是虚的
        sendDataMap.put("locationFrom",locationFrom);
        //目的暂存位（点位信息）---这才是重点，上面的都是虚的
        sendDataMap.put("locationTo",locationTo);
        agvTask.setLocationTo(locationTo);
        //优先级(数字越大优先级越高)
        sendDataMap.put("priority","1");
        //用以分区相同设备不同动作的流程
        sendDataMap.put("extParam","1");
        //拓展参数1
        sendDataMap.put("ext1","1");
        //拓展参数2
        sendDataMap.put("ext2","1");
        //拓展参数3
        sendDataMap.put("ext3","1");
        //来源库区,支持多个库区
        List<Map<String, Object>> areaFromList = new ArrayList<>();
        areaFromList.add(new HashMap<String, Object>(1){{
            put("areaCode","222");
        }});
        areaFromList.add(new HashMap<String, Object>(1){{
            put("areaCode","333");
        }});
        sendDataMap.put("areaFrom",areaFromList);
        //目的库区,支持多个库区
        List<Map<String, Object>> areaTo = new ArrayList<>();
        areaTo.add(new HashMap<String, Object>(1){{
            put("areaCode","555");
        }});
        areaTo.add(new HashMap<String, Object>(1){{
            put("areaCode","666");
        }});
        sendDataMap.put("areaTo",areaTo);
        //调用AMS生成AGV任务的接口
        String returnResult = Rbsc.httpPostWithJSON("http://10.102.11.242:7080/api/HHAms/AddTask", JSONObject.toJSONString(sendDataMap));
        //记录接口日志：生成了搬运任务后发送给AMS
        interfaceLogDAO.insertLog("AddTask","WMS-->>AMS 生成AGV任务发送给AMS", JSONObject.toJSONString(sendDataMap), returnResult,
                //AGV任务号，物料对应的批次号
                (String) sendDataMap.get("taskNo"), (String) sendDataMap.get("batchNo"));
        //生成的任务存入agv任务表
        agvTask.setBussinessType(EmumConstant.agvTaskType.WAREHOUSING.getCode());
        agvTask.setWhNoFrom(null);
        agvTask.setWhNoTo(null);
        agvTask.setTaskNo(taskNo);
        agvTask.setBatchNo(batch_no);
        agvTask.setLocationFrom(locationFrom);
        agvTask.setLocationTo(locationTo);
        agvTask.setDeliveryNum(num);
        agvTask.setMaterialCode(null);
        agvTaskDAO.insert(agvTask);
        return returnResult;
    }

    /**
     * 退空托架
     * @return String
     */
    @Override
    public String returnBracketTask(){
        //退空托接口，把要退空托的机台库位信息发送给WMS
        String locationFrom =null;


        //循环库位表中所有得库位得到一个空库位作为目的库位
        List<Shelf> lstTargetShelf = shelfDAO.selectList(new EntityWrapper<Shelf>()
                .eq("AREA", EmumConstant.shelfArea.EMPTY_TRAY_AREA.getCode())
                .eq("STATE",EmumConstant.sheflState.AVAILABLE.getCode())
                .isNotNull("AGV_POINT"));
        String locationTo = null;
        for(Shelf shelf : lstTargetShelf){//循环查询readStockStatus接口查询空接口
            Map<String, Object>  readStock = readStockStatus(Integer.parseInt(shelf.getAgvPoint()));
            if(readStock.get("occupy").equals("0")){//1非空0空9点位不存在
                locationTo = shelf.getAgvPoint();
                break;
            }
        }
        //如果没有空位得话提示返回，有的话确认是目标暂存位置
        if (locationTo.isEmpty()){
            return JSONObject.toJSONString(new HashMap<String, Object>(3){{
                put("success", "False");
                put("errCode", "001");
                put("errMsg", "没有可用的目标暂存位，空托盘库区库位已满！");
            }});
        }
        AgvTask agvTask = new AgvTask();
        Map<String,Object> sendDataMap = Maps.newHashMap();
        //2：叫料
        sendDataMap.put("businessType", "1");
        //来源仓库号（调拨单中的调出子库）
        sendDataMap.put("whNoFrom",null);
        //目的仓库号（调拨单中的调入子库）
        sendDataMap.put("whNoTo",null);
        //系统名称？
        sendDataMap.put("sysName",null);
        //设备名称？
        sendDataMap.put("deviceCode",null);
        //wms生成的最新agv任务号
        String taskNo = new DecimalFormat("000000000000").format(webApiDAO.selectSeqAgvTaskNo());
        sendDataMap.put("taskNo",taskNo);
        //批次号（物料的批次号）
        sendDataMap.put("batchNo",null);
        //任务序号、生成任务按照升序规则，不填默认为0
        sendDataMap.put("orderNo",0);
        //来源暂存位（点位信息）---这才是重点，上面的都是虚的
        sendDataMap.put("locationFrom",locationFrom);
        //目的暂存位（点位信息）---这才是重点，上面的都是虚的
        sendDataMap.put("locationTo",locationTo);
        agvTask.setLocationTo(locationTo);
        //优先级(数字越大优先级越高)
        sendDataMap.put("priority","1");
        //用以分区相同设备不同动作的流程
        sendDataMap.put("extParam","1");
        //拓展参数1
        sendDataMap.put("ext1","1");
        //拓展参数2
        sendDataMap.put("ext2","1");
        //拓展参数3
        sendDataMap.put("ext3","1");
        //来源库区,支持多个库区
        List<Map<String, Object>> areaFromList = new ArrayList<>();
        areaFromList.add(new HashMap<String, Object>(1){{
            put("areaCode","222");
        }});
        areaFromList.add(new HashMap<String, Object>(1){{
            put("areaCode","333");
        }});
        sendDataMap.put("areaFrom",areaFromList);
        //目的库区,支持多个库区
        List<Map<String, Object>> areaTo = new ArrayList<>();
        areaTo.add(new HashMap<String, Object>(1){{
            put("areaCode","555");
        }});
        areaTo.add(new HashMap<String, Object>(1){{
            put("areaCode","666");
        }});
        sendDataMap.put("areaTo",areaTo);
        //调用AMS生成AGV任务的接口
        String returnResult = Rbsc.httpPostWithJSON("http://10.102.11.242:7080/api/HHAms/AddTask", JSONObject.toJSONString(sendDataMap));
        //记录接口日志：生成了搬运任务后发送给AMS
        interfaceLogDAO.insertLog("AddTask","WMS-->>AMS 生成AGV任务发送给AMS", JSONObject.toJSONString(sendDataMap), returnResult,
                //AGV任务号，物料对应的批次号
                (String) sendDataMap.get("taskNo"), (String) sendDataMap.get("batchNo"));
        //生成的任务存入agv任务表
        agvTask.setBussinessType(EmumConstant.agvTaskType.WAREHOUSING.getCode());
        agvTask.setWhNoFrom(null);
        agvTask.setWhNoTo(null);
        agvTask.setTaskNo(taskNo);
        agvTask.setLocationFrom(locationFrom);
        agvTask.setLocationTo(locationTo);
        agvTask.setMaterialCode(null);
        agvTaskDAO.insert(agvTask);
        return returnResult;
    }


    /**
     * 退固废
     * @return String
     */
    @Override
    public String returnSolidWasteTask(){
        //退废料接口，把要退废料的机台及货位信息发送给WMS
        String locationFrom =null;


        //循环库位表中所有得库位得到一个空库位作为目的库位
        List<Shelf> lstTargetShelf = shelfDAO.selectList(new EntityWrapper<Shelf>()
                .eq("AREA", EmumConstant.shelfArea.WASTE_AREA.getCode())
                .eq("STATE",EmumConstant.sheflState.AVAILABLE.getCode())
                .isNotNull("AGV_POINT"));
        String locationTo = null;
        for(Shelf shelf : lstTargetShelf){//循环查询readStockStatus接口查询空接口
            Map<String, Object>  readStock = readStockStatus(Integer.parseInt(shelf.getAgvPoint()));
            if(readStock.get("occupy").equals("0")){//1非空0空9点位不存在
                locationTo = shelf.getAgvPoint();
                break;
            }
        }
        //如果没有空位得话提示返回，有的话确认是目标暂存位置
        if (locationTo.isEmpty()){
            return JSONObject.toJSONString(new HashMap<String, Object>(3){{
                put("success", "False");
                put("errCode", "001");
                put("errMsg", "没有可用的目标暂存位，空托盘库区库位已满！");
            }});
        }
        AgvTask agvTask = new AgvTask();
        Map<String,Object> sendDataMap = Maps.newHashMap();
        //2：叫料
        sendDataMap.put("businessType", "1");
        //来源仓库号（调拨单中的调出子库）
        sendDataMap.put("whNoFrom",null);
        //目的仓库号（调拨单中的调入子库）
        sendDataMap.put("whNoTo",null);
        //系统名称？
        sendDataMap.put("sysName",null);
        //设备名称？
        sendDataMap.put("deviceCode",null);
        //wms生成的最新agv任务号
        String taskNo = new DecimalFormat("000000000000").format(webApiDAO.selectSeqAgvTaskNo());
        sendDataMap.put("taskNo",taskNo);
        //批次号（物料的批次号）
        sendDataMap.put("batchNo",null);
        //任务序号、生成任务按照升序规则，不填默认为0
        sendDataMap.put("orderNo",0);
        //来源暂存位（点位信息）---这才是重点，上面的都是虚的
        sendDataMap.put("locationFrom",locationFrom);
        //目的暂存位（点位信息）---这才是重点，上面的都是虚的
        sendDataMap.put("locationTo",locationTo);
        agvTask.setLocationTo(locationTo);
        //优先级(数字越大优先级越高)
        sendDataMap.put("priority","1");
        //用以分区相同设备不同动作的流程
        sendDataMap.put("extParam","1");
        //拓展参数1
        sendDataMap.put("ext1","1");
        //拓展参数2
        sendDataMap.put("ext2","1");
        //拓展参数3
        sendDataMap.put("ext3","1");
        //来源库区,支持多个库区
        List<Map<String, Object>> areaFromList = new ArrayList<>();
        areaFromList.add(new HashMap<String, Object>(1){{
            put("areaCode","222");
        }});
        areaFromList.add(new HashMap<String, Object>(1){{
            put("areaCode","333");
        }});
        sendDataMap.put("areaFrom",areaFromList);
        //目的库区,支持多个库区
        List<Map<String, Object>> areaTo = new ArrayList<>();
        areaTo.add(new HashMap<String, Object>(1){{
            put("areaCode","555");
        }});
        areaTo.add(new HashMap<String, Object>(1){{
            put("areaCode","666");
        }});
        sendDataMap.put("areaTo",areaTo);
        //调用AMS生成AGV任务的接口
        String returnResult = Rbsc.httpPostWithJSON("http://10.102.11.242:7080/api/HHAms/AddTask", JSONObject.toJSONString(sendDataMap));
        //记录接口日志：生成了搬运任务后发送给AMS
        interfaceLogDAO.insertLog("AddTask","WMS-->>AMS 生成AGV任务发送给AMS", JSONObject.toJSONString(sendDataMap), returnResult,
                //AGV任务号，物料对应的批次号
                (String) sendDataMap.get("taskNo"), (String) sendDataMap.get("batchNo"));
        //生成的任务存入agv任务表
        agvTask.setBussinessType(EmumConstant.agvTaskType.WAREHOUSING.getCode());
        agvTask.setWhNoFrom(null);
        agvTask.setWhNoTo(null);
        agvTask.setTaskNo(taskNo);
        agvTask.setLocationFrom(locationFrom);
        agvTask.setLocationTo(locationTo);
        agvTask.setMaterialCode(null);
        agvTaskDAO.insert(agvTask);
        return returnResult;
    }

    /**
     * 空具盘转移
     * @return String
     */
    @Override
    public String emptyDiskTask(){
        //遍历所有的盘具区域库位，检测下线点位的满情况
        List<Shelf> lstTargetLowShelf = shelfDAO.selectList(new EntityWrapper<Shelf>()
                .eq("AREA", EmumConstant.shelfArea.EMPTY_DISH_AREA.getCode())
                .eq("STATE",EmumConstant.sheflState.OCCUPY.getCode())
                .isNotNull("AGV_POINT"));
        String locationFrom = null;
        for(Shelf shelf : lstTargetLowShelf){//循环查询readStockStatus接口查询空接口
            Map<String, Object>  readStock = readStockStatus(Integer.parseInt(shelf.getAgvPoint()));
            if(readStock.get("occupy").equals("1")){//1非空0空9点位不存在
                locationFrom = shelf.getAgvPoint();
                break;
            }
        }


        //遍历所有的盘具区域库位，检测上线点位的空情况
        List<Shelf> lstTargetShelf = shelfDAO.selectList(new EntityWrapper<Shelf>()
                .eq("AREA", EmumConstant.shelfArea.EMPTY_DISH_AREA.getCode())
                .eq("STATE",EmumConstant.sheflState.AVAILABLE.getCode())
                .isNotNull("AGV_POINT"));
        String locationTo = null;
        for(Shelf shelf : lstTargetShelf){//循环查询readStockStatus接口查询空接口
            Map<String, Object>  readStock = readStockStatus(Integer.parseInt(shelf.getAgvPoint()));
            if(readStock.get("occupy").equals("0")){//1非空0空9点位不存在
                locationTo = shelf.getAgvPoint();
                break;
            }
        }
        AgvTask agvTask = new AgvTask();
        Map<String,Object> sendDataMap = Maps.newHashMap();
        //2：叫料
        sendDataMap.put("businessType", "1");
        //来源仓库号（调拨单中的调出子库）
        sendDataMap.put("whNoFrom",null);
        //目的仓库号（调拨单中的调入子库）
        sendDataMap.put("whNoTo",null);
        //系统名称？
        sendDataMap.put("sysName",null);
        //设备名称？
        sendDataMap.put("deviceCode",null);
        //wms生成的最新agv任务号
        String taskNo = new DecimalFormat("000000000000").format(webApiDAO.selectSeqAgvTaskNo());
        sendDataMap.put("taskNo",taskNo);
        //批次号（物料的批次号）
        sendDataMap.put("batchNo",null);
        //任务序号、生成任务按照升序规则，不填默认为0
        sendDataMap.put("orderNo",0);
        //来源暂存位（点位信息）---这才是重点，上面的都是虚的
        sendDataMap.put("locationFrom",locationFrom);
        //目的暂存位（点位信息）---这才是重点，上面的都是虚的
        sendDataMap.put("locationTo",locationTo);
        agvTask.setLocationTo(locationTo);
        //优先级(数字越大优先级越高)
        sendDataMap.put("priority","1");
        //用以分区相同设备不同动作的流程
        sendDataMap.put("extParam","1");
        //拓展参数1
        sendDataMap.put("ext1","1");
        //拓展参数2
        sendDataMap.put("ext2","1");
        //拓展参数3
        sendDataMap.put("ext3","1");
        //来源库区,支持多个库区
        List<Map<String, Object>> areaFromList = new ArrayList<>();
        areaFromList.add(new HashMap<String, Object>(1){{
            put("areaCode","222");
        }});
        areaFromList.add(new HashMap<String, Object>(1){{
            put("areaCode","333");
        }});
        sendDataMap.put("areaFrom",areaFromList);
        //目的库区,支持多个库区
        List<Map<String, Object>> areaTo = new ArrayList<>();
        areaTo.add(new HashMap<String, Object>(1){{
            put("areaCode","555");
        }});
        areaTo.add(new HashMap<String, Object>(1){{
            put("areaCode","666");
        }});
        sendDataMap.put("areaTo",areaTo);
        //调用AMS生成AGV任务的接口
        String returnResult = Rbsc.httpPostWithJSON("http://10.102.11.242:7080/api/HHAms/AddTask", JSONObject.toJSONString(sendDataMap));
        //记录接口日志：生成了搬运任务后发送给AMS
        interfaceLogDAO.insertLog("AddTask","WMS-->>AMS 生成AGV任务发送给AMS", JSONObject.toJSONString(sendDataMap), returnResult,
                //AGV任务号，物料对应的批次号
                (String) sendDataMap.get("taskNo"), (String) sendDataMap.get("batchNo"));
        //生成的任务存入agv任务表
        agvTask.setBussinessType(EmumConstant.agvTaskType.WAREHOUSING.getCode());
        agvTask.setWhNoFrom(null);
        agvTask.setWhNoTo(null);
        agvTask.setTaskNo(taskNo);
        agvTask.setLocationFrom(locationFrom);
        agvTask.setLocationTo(locationTo);
        agvTask.setMaterialCode(null);
        agvTaskDAO.insert(agvTask);
        return returnResult;
    }


    /**
     * 查询光感，判断库位上是否有托盘
     * @param station 点位编号
     * @return String
     */
    @Override
    public Map<String, Object> readStockStatus(Integer station){
        String returnJsonString = Rbsc.httpPostWithJSON("http://10.102.11.242:7080/api/HHAms/ReadStockStatus",
                JSONObject.toJSONString(new HashMap<String,Object>(1){{
                    put("station", station);
                }}));
        logger.info("查询光感，判断库位上是否有托盘："+returnJsonString);
        return  (Map<String, Object>) com.alibaba.fastjson.JSONObject.parse(returnJsonString);
    }


}
